package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        // 获取到命名空间的值
        String namespace = rootElement.attributeValue("namespace");
        Map<String, MappedStatement> sqlMappedStatementMap = configuration.getSqlMappedStatementMap();
        // 解析xml中select相关的方法
        List<Element> list = rootElement.selectNodes("//select");
        for (Element selectElement : list) {
            mappedStatementBinding(selectElement,namespace,sqlMappedStatementMap);
        }

        // 解析mapper.xml中insert相关的方法
        List<Element> insertList = rootElement.selectNodes("//insert");
        for (Element insertElement : insertList) {
            // 解析mapper.xml中insert相关的方法,组合更新key和对应的mappedStatement
            mappedStatementBinding(insertElement,namespace,sqlMappedStatementMap);
        }

        List<Element> updateList = rootElement.selectNodes("//update");
        for (Element updateElement : updateList) {
            // 解析mapper.xml中update相关的方法,组合更新key和对应的mappedStatement
            mappedStatementBinding(updateElement,namespace,sqlMappedStatementMap);
        }

        List<Element> deleteList = rootElement.selectNodes("//delete");
        for (Element deleteElement : deleteList) {
            // 解析mapper.xml中delete相关的方法,组合更新key和对应的mappedStatement
            mappedStatementBinding(deleteElement,namespace,sqlMappedStatementMap);
        }
    }

    /**
     * 解析xml各种方法，进行赋值到mappedStatement
     *
     * @param element element
     * @param namespace namespace
     * @param sqlMappedStatementMap sqlMappedStatementMap
     */
    private void mappedStatementBinding(Element element,String namespace, Map<String, MappedStatement> sqlMappedStatementMap) {
        String id = element.attributeValue("id");
        MappedStatement mappedStatement = new MappedStatement();
        mappedStatement.setId(id);
        mappedStatement.setParamterType(element.attributeValue("paramterType"));
        mappedStatement.setResultType(element.attributeValue("resultType"));
        mappedStatement.setSql(element.getTextTrim());
        // 组合删除key和对应的mappedStatement
        sqlMappedStatementMap.put(namespace+"."+id, mappedStatement);
    }

}
